---
title: "Example: Hybrid Vector Search | RAG"
description: Example of using metadata filters with PGVector to enhance vector search results in Mastra.
---

import GithubLink from "@site/src/components/GithubLink";

# Hybrid Vector Search

When you combine vector similarity search with metadata filters, you can create a hybrid search that is more precise and efficient.
This approach combines:

- Vector similarity search to find the most relevant documents
- Metadata filters to refine the search results based on additional criteria

This example demonstrates how to use hybrid vector search with Mastra and PGVector.

## Overview

The system implements filtered vector search using Mastra and PGVector. Here's what it does:

1. Queries existing embeddings in PGVector with metadata filters
2. Shows how to filter by different metadata fields
3. Demonstrates combining vector similarity with metadata filtering

> **Note**: For examples of how to extract metadata from your documents, see the [Metadata Extraction](../embedding/metadata-extraction) guide.
>
> To learn how to create and store embeddings, see the [Vector Databases](/docs/v1/rag/vector-databases) guide.

## Setup

### Environment Setup

Make sure to set up your environment variables:

```bash title=".env"
OPENAI_API_KEY=your_openai_api_key_here
POSTGRES_CONNECTION_STRING=your_connection_string_here
```

### Dependencies

Import the necessary dependencies:

```typescript copy showLineNumbers title="src/index.ts"
import { embed } from "ai";
import { PgVector } from "@mastra/pg";
import { ModelRouterEmbeddingModel } from "@mastra/core/llm";
```

## Vector Store Initialization

Initialize PgVector with your connection string:

```typescript copy showLineNumbers{4} title="src/index.ts"
const pgVector = new PgVector({
  id: 'rag-vectors',
  connectionString: process.env.POSTGRES_CONNECTION_STRING!,
});
```

## Example Usage

### Filter by Metadata Value

```typescript copy showLineNumbers{3} title="src/index.ts"
// Create embedding for the query
const { embedding } = await embed({
  model: new ModelRouterEmbeddingModel("openai/text-embedding-3-small"),
  value: "[Insert query based on document here]",
});

// Query with metadata filter
const result = await pgVector.query({
  indexName: "embeddings",
  queryVector: embedding,
  topK: 3,
  filter: {
    "path.to.metadata": {
      $eq: "value",
    },
  },
});

console.log("Results:", result);
```

<br />
<br />
<hr className="dark:border-[#404040] border-gray-300" />
<br />
<br />
<GithubLink
  href={
    "https://github.com/mastra-ai/mastra/blob/main/examples/basics/rag/hybrid-vector-search"
  }
/>
